package ArryProTest;

import java.util.Arrays;

//二分法查找
public class MidTest {
    public static void main(String[] args) {
        int[] arr = {10,20,30,50,70,90,100,101};
        //所要查找的数
        int searchWord = 100;
        //二分法查找前一定要对数组元素进行排序
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        System.out.println(searchWord+"元素的索引位置："+binArySearch(arr,searchWord));


    }
    public static int binArySearch(int[] array,int value){
        int low = 0;
        int high = array.length-1;
        while(low <= high){
            int middle = (low + high)/2;
            if (value == array[middle]){
                //返回查询到的索引位置
                return middle;
            }else if (value > array[middle]){
                low = middle + 1;
            }else{
                low = middle - 1 ;
            }
        }
        //上面循环完毕，说明未找到，返回-1
        return -1;

    }
}

